package com.meihua.baoleyi.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.meihua.baoleyi.R;
import com.meihua.baoleyi.bean.ShopCart;
import com.meihua.baoleyi.bean.WXPayBean;
import com.meihua.baoleyi.common.APIServer;
import com.meihua.baoleyi.common.MyApp;
import com.meihua.baoleyi.dialog.ClearCacheDialog;
import com.meihua.baoleyi.net.NetHelper;
import com.meihua.baoleyi.utils.IsPayPasswordUtil;
import com.meihua.baoleyi.utils.ToastUtil;
import com.meihua.baoleyi.widget.AlertDialog;
import com.meihua.baoleyi.widget.CustomerKeyboard;
import com.meihua.baoleyi.widget.PasswordEditText;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.TreeMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 简单通用的h5
 */

public class CommonWebActivity extends BaseWebViewActivity implements CustomerKeyboard.CustomerKeyboardClickListener, PasswordEditText.PasswordFullListener {

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 1;

    @Bind(R.id.text_title)
    TextView tvTitle;//标题
    @Bind(R.id.common_problem_webview)
    WebView webview;//web页面
    @Bind(R.id.text_back)
    ImageView mIVTopLeft;//返回键
    @Bind(R.id.main_iv_cart)
    ImageView mIVCart;//购物车
    @Bind(R.id.cart_del)
    ImageView cart_del;//删除键
    @Bind(R.id.loading)
    ProgressBar mLoading;//加载进度
    @Bind(R.id.iv_red_point)
    ImageView ivRedPoint; //红点

    private String mPhone; //客服电话号

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_detail);
        ButterKnife.bind(this);
        initView();
    }

    /*初始化View*/
    public void initView() {
        String url = getIntent().getStringExtra("url");
        if (url.contains("goodsDetail")) mIVCart.setVisibility(View.VISIBLE);
        if (url.contains("shopCat")) cart_del.setVisibility(View.VISIBLE);
        tvTitle.setVisibility(View.VISIBLE);
        mIVTopLeft.setVisibility(View.VISIBLE);
        webview.addJavascriptInterface(new AndroidToJs(), "android");
        initWebView(webview, mLoading, url, tvTitle);

        if (mIVCart.getVisibility() == View.VISIBLE) {
            isShoppingCatEmpty();
        }
    }

    /*以下三个方法是输入支付密码弹框*/
    @Override
    public void click(String numder) {
        passwordEditText.addPassword(numder);
    }

    @Override
    public void delete() {
        passwordEditText.deleteLastPassword();
    }

    @Override
    public void passwordFull(final String password) {
        getServerData(CommonWebActivity.this.mStatus, CommonWebActivity.this.mID, password);
        dialog.dismiss();
    }


    /**
     * 请求数据
     *
     * @param status
     * @param id
     */
    private void getServerData(final String status, String id, String pwd) {
        /*验证支付密码*/
        TreeMap<String, String> params = new TreeMap<String, String>();
        params.put("user_id", MyApp.getInstance().getUser_id());
        params.put("order_id", id);
        params.put("status", status);
        params.put("pay_password", pwd);
        NetHelper.post(APIServer.ORDERPAY, params, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                /*请求得到的数据*/
                WXPayBean bean = NetHelper.getBeanForJson(WXPayBean.class, s);
                if (bean != null) {
                    if (status.equals("1")) {
                        wxPay(bean);
                    } else if (status.equals("2")) {
                        if (bean.getCode().equals("200")) {
                            startActivity(new Intent(CommonWebActivity.this, MyOrderActivity.class));
                            finish();
                        }
                        //余额支付
                        Toast.makeText(CommonWebActivity.this, bean.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private String mStatus;
    private String mID;

    /*js调用Android*/
    class AndroidToJs {
        /*支付*/
        @JavascriptInterface
        public void go_pay(String status, String id, String num) {
            CommonWebActivity.this.mStatus = status;
            CommonWebActivity.this.mID = id;
            if (status.equals("1")) {//微信支付
                getServerData(status, id, "");
            } else if (status.equals("2")) {//余额支付
                //判断是否设置了支付密码
                IsPayPasswordUtil.isPayPassword(CommonWebActivity.this, new IsPayPasswordUtil.OnIsPayPassword() {
                    @Override
                    public void isSetPayPassword(boolean isSet) {
                        if (isSet) {
                            //弹出输入密码对话框
                            showCustomInputDialog();
                        }
                    }
                });
            } else {//银行卡支付
                ToastUtil.show(CommonWebActivity.this, "银行卡服务暂时没有开通");
            }
        }

        /*关闭界面*/
        @JavascriptInterface
        public void closeWeb() {
            CommonWebActivity.this.finish();
        }

        /**
         * 拨打电话
         */
        @JavascriptInterface
        public void call(String phone) {
            mPhone = phone;
            callDialog();
        }

        /**
         * 查看大图
         */
        @JavascriptInterface
        public void showBigImage(String urlStr, int imageIndex) {
            if (urlStr != null && !urlStr.equals("")) {
                Intent intent = new Intent(CommonWebActivity.this, PhotoShowActivity.class);
                intent.putExtra("imageUrl", urlStr);
                intent.putExtra("imageIndex", imageIndex);
                startActivity(intent);
            }
        }
    }

    /*微信支付*/
    private void wxPay(WXPayBean wx) {
        try {
            if (wx.getCode().equals("1")) {
                //调用微信支付
                IWXAPI mWxApi = WXAPIFactory.createWXAPI(CommonWebActivity.this, wx.getData().getAppid(), true);
                mWxApi.registerApp(wx.getData().getAppid());
                PayReq req = new PayReq();
                req.appId = wx.getData().getAppid();// 微信开放平台审核通过的应用APPID
                req.partnerId = wx.getData().getMch_id();// 微信支付分配的商户号
                req.prepayId = wx.getData().getPrepay_id();// 预支付订单号，app服务器调用“统一下单”接口获取
                req.packageValue = "Sign=WXPay";// 固定值Sign=WXPay，可以直接写死，服务器返回的也是这个固定值
                req.nonceStr = wx.getData().getNonce_str();// 随机字符串，不长于32位，服务器小哥会给咱生成
                req.timeStamp = wx.getData().getTimestamp() + "";// 时间戳，app服务器小哥给出
                req.sign = wx.getData().getSign();// 签名，服务器小哥给出，他会根据：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3指导得到这个
                mWxApi.sendReq(req);
                finish();
            } else {
                Toast.makeText(CommonWebActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(CommonWebActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }


    /*点击事件*/
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @OnClick({R.id.text_back, R.id.main_iv_cart, R.id.cart_del})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cart_del: //
                mWebView.loadUrl("javascript:del()");
                break;
            case R.id.text_back:
                finish();
                break;
            case R.id.main_iv_cart://购物车
                Intent intent = new Intent(this, CommonWebActivity.class);
                intent.putExtra("url", APIServer.SHOPCAT + MyApp.getInstance().getToken() + "/" + MyApp.getInstance().getUser_id());
                startActivity(intent);
                break;
        }
    }

    private PasswordEditText passwordEditText;
    private CustomerKeyboard mCustomerKeyboard;
    private AlertDialog dialog;

    /*弹出输入密码对话框*/
    private void showCustomInputDialog() {
        if (dialog != null) {
            return;
        }
        //弹出dialog输入框
        dialog = new AlertDialog.Builder(this).
                setContentView(R.layout.activity_password).
                fullWith().
                setCancelable(true).
                formBottom(true).
                show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog1) {
                dialog = null;
            }
        });
        passwordEditText = dialog.getView(R.id.password);
        mCustomerKeyboard = dialog.getView(R.id.customer_keyboard);
        mCustomerKeyboard.setOnCustomerKeyboardClickListener(this);
        passwordEditText.setEnabled(false);
        passwordEditText.setOnPasswordFullListener(this);
    }

    /**
     * 拨打客服对话框
     */
    private void callDialog() {
        if (mPhone.isEmpty()) {
            return;
        }
        ClearCacheDialog dlg = new ClearCacheDialog.Builder(this)
                .setMessage(mPhone)
                .setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        call(mPhone);
                        dialogInterface.dismiss();
                    }
                })
                .setNativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .build();
        dlg.show();
    }

    /**
     * 调用拨号功能
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        if (Build.VERSION.SDK_INT > 22 && (ContextCompat.checkSelfPermission(CommonWebActivity.this,
                Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED)) {
            //先判断有没有权限 ，没有就在这里进行权限的申请
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else {
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
            this.startActivity(intent);
        }
    }

    /**
     * 权限获取回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                call(mPhone); //拨打电话
            } else {
                Toast.makeText(CommonWebActivity.this, "权限获取失败", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mIVCart.getVisibility() == View.VISIBLE) {
            isShoppingCatEmpty();
        }
    }

    public void isShoppingCatEmpty() {
        TreeMap<String, String> treeMap = new TreeMap<String, String>() {
            {
                put("user_id", MyApp.getInstance().getUser_id());
            }
        };
        NetHelper.get(APIServer.GET_SHOPCART, treeMap, true, new NetHelper.HttpCallBack() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                ShopCart bean = NetHelper.getBeanForJson(ShopCart.class, s);
                if (bean == null) return;
                if (bean.getCode().equals("200")) {
                    if (null != bean.getData()) {
                        if (bean.getData().size() != 0) {
                            if (ivRedPoint != null) {
                                ivRedPoint.setVisibility(View.VISIBLE);
                            }
                        } else {
                            if (ivRedPoint != null) {
                                ivRedPoint.setVisibility(View.GONE);
                            }
                        }
                    }
                }

            }
        });
    }

}
